package com.etaoking.commons;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import play.Logger;
import play.cache.Cache;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.ItemCat;
import com.taobao.api.domain.PropValue;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.TaobaokeShop;
import com.taobao.api.domain.Trade;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ItempropvaluesGetRequest;
import com.taobao.api.request.TaobaokeItemsGetRequest;
import com.taobao.api.request.TaobaokeShopsGetRequest;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.request.TradesBoughtGetRequest;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ItempropvaluesGetResponse;
import com.taobao.api.response.TaobaokeItemsGetResponse;
import com.taobao.api.response.TaobaokeShopsGetResponse;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.taobao.api.response.TradesBoughtGetResponse;

/**
 * 
 * 淘宝工具类
 * 
 * @author Administrator
 *
 */
public class TaobaoUtils {
	
	public static void saveFile(String path,String content){
		if(content!=null && !content.equals("")){
			FileWriter fw;
			try {
				fw = new FileWriter(new File(path));
				fw.write(content);
				fw.flush();
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		List<ItemCat> result = getItemCats(0L,"50018004,");
		System.out.println(result.size());
	}
	
	/**
	 * 得到根分类
	 * 
	 * @return
	 */
	public static List<ItemCat> getRootItemCats(){
		return getItemCats(0L,null);
	}
	/**
	 * 获取后台供卖家发布商品的标准商品类目
	 */
	public static List<ItemCat> getItemCats(Long parentCid,String cids){
		List<ItemCat> itemCats = Cache.get(parentCid==null?"":parentCid+"_"+cids, List.class);
		if(itemCats!=null)return itemCats;
		Logger.info("%s", "查询淘宝分类!");
		TaobaoClient client = getDefaultTaobaoClient();
		ItemcatsGetRequest req=new ItemcatsGetRequest();
		req.setFields("cid,parent_cid,name,is_parent");
		if(parentCid!=null)req.setParentCid(parentCid);
		if(!"".equals(cids))req.setCids(cids);
		try {
			ItemcatsGetResponse response = client.execute(req);
			itemCats = response.getItemCats();
			if(itemCats!=null && itemCats.size()>0)
				Cache.set(parentCid==null?"":parentCid+"_"+cids, itemCats,"30mn");
			return itemCats;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<TaobaokeItem> getTaobaokeItems(Long cid,Long pageNo,Long pageSize){
		return getTaobaokeItems(cid,pageNo,pageSize,"liuzi0733");
	}
	
	/**
	 * 查询淘宝客推广商品
	 */
	public static List<TaobaokeItem> getTaobaokeItems(Long cid,Long pageNo,Long pageSize,String nick){
		Logger.info("%s", "查询淘宝客推广商品!");
		TaobaoClient client = getDefaultTaobaoClient();
		TaobaokeItemsGetRequest req=new TaobaokeItemsGetRequest();
		req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
		req.setNick(nick);
		req.setCid(cid);
		req.setPageNo(pageNo);
		req.setPageSize(pageSize);
		req.setStartPrice("1");
		req.setEndPrice("999");
		TaobaokeItemsGetResponse response;
		try {
			response = client.execute(req);
			List<TaobaokeItem> taobaokeItems = response.getTaobaokeItems();
//			if(taobaokeItems!=null){
//				StringBuffer sb = new StringBuffer("");
//				for (TaobaokeItem taobaokeItem : taobaokeItems) {
//					sb.append("clickUrl:"+taobaokeItem.getClickUrl());
//					sb.append("pic_url:"+taobaokeItem.getPicUrl());
//					sb.append("nick:"+taobaokeItem.getNick());
//					sb.append("price:"+taobaokeItem.getPrice());
//					sb.append("title:"+taobaokeItem.getTitle());
//					sb.append("KeywordClickUrl:"+taobaokeItem.getKeywordClickUrl());
//					sb.append("\n");
//				}
//				TaobaoUtils.saveFile("D:/TaobaokeItems.txt", sb.toString());
//			}
			return taobaokeItems;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取站长推荐商品
	 * 
	 * @param cid
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public static List<TaobaokeItem> getRecommendItems(Long cid,Long pageNo,Long pageSize){
		List<TaobaokeItem> RecommendItems = Cache.get("recommend_product",List.class);
		if(RecommendItems != null && RecommendItems.size() == 0)return RecommendItems;
		RecommendItems = getTaobaokeItems(cid,pageNo,pageSize);
		Cache.set("recommend_product",RecommendItems,"30mn");
		return RecommendItems;
	}
	
	public void getPropValues(){
		TaobaoClient client = getDefaultTaobaoClient();
		ItempropvaluesGetRequest req=new ItempropvaluesGetRequest();
		req.setFields("cid,pid,prop_name,vid,name,name_alias,status,sort_order");
		req.setCid(50008898L);
		try {
			ItempropvaluesGetResponse response = client.execute(req);
			List<PropValue> propValues = response.getPropValues();
			if(propValues!=null){
				StringBuffer sb = new StringBuffer("");
				for (PropValue propValue : propValues) {
					sb.append("cid:"+propValue.getCid());
					sb.append("prop_name:"+propValue.getPropName());
					sb.append("vid:"+propValue.getVid());
					sb.append("name:"+propValue.getName());
					sb.append("name_alias:"+propValue.getNameAlias());
					sb.append("\n");
				}
				TaobaoUtils.saveFile("D:/PropValues.txt", sb.toString());
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取推荐店铺信息
	 * 
	 * @return
	 */
	public static List<TaobaokeShop> getTaobaokeShops(){
		TaobaoClient client=getDefaultTaobaoClient();
		TaobaokeShopsGetRequest req=new TaobaokeShopsGetRequest();
		req.setFields("user_id,click_url,shop_title,commission_rate,seller_credit,shop_type,auction_count,total_auction");
		req.setStartCredit("1crown");
		req.setEndCredit("5goldencrown");
		req.setCid(16L);
//		req.setStartCommissionrate("50");
//		req.setEndCommissionrate("150");
//		req.setStartAuctioncount("10");
//		req.setEndAuctioncount("200");
//		req.setStartTotalaction("10");
//		req.setEndTotalaction("200");
		req.setPageNo(1L);
		req.setPageSize(10L);
		req.setNick("liuzi0733");
		try {
			TaobaokeShopsGetResponse response = client.execute(req);
			return response.getTaobaokeShops();
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 获取所有订单
	 * 
	 * @return
	 */
	public static List<Trade> getTrades(){
		Logger.info("访问淘宝订单列表!");
		TaobaoClient client = getDefaultTaobaoClient();
		TradesBoughtGetRequest req=new TradesBoughtGetRequest();
		req.setPageNo(new Long(1));
		req.setPageSize(new Long(50));
		req.setFields("seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type");
		try {
			TradesBoughtGetResponse response = client.execute(req , Contants.UserInfo.current().sessionKey);
			List<Trade> trades = response.getTrades();
			return trades;
		} catch (ApiException e) {
			Logger.error("访问淘宝接口出错!",e);
		}
		return null;
	}

	public static TaobaoClient getDefaultTaobaoClient() {
		TaobaoClient client=new DefaultTaobaoClient(Contants.url, Contants.appKey, Contants.secret);
		return client;
	}
	
	/**
	 * 获取交易全信息
	 * 
	 * @param tid
	 * @return
	 */
	public static Trade getTrade(Long tid){
		TaobaoClient client= getDefaultTaobaoClient();
		TradeFullinfoGetRequest req=new TradeFullinfoGetRequest();
		req.setFields("seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type");
		req.setTid(tid);
		try {
			TradeFullinfoGetResponse response = client.execute(req , Contants.UserInfo.current().sessionKey);
			Trade trade = response.getTrade();
			return trade;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
}
